<?php
class FlightController extends AppController{
    var $name = 'Flight';
	//使用User,Flight,Plane,BookInfo,Quene这五个Modul
	var $uses = array('User','Flight','Plane','BookInfo','Quene','Airport');
    var $components = array('Email'); 
    //beforeFilter 页面执行前执行
	//afterFilter 页面执行后执行
	//beforeRender 页面显示前执行
	//afterRender 页面显示后执
	
    function beforeFilter(){
		Configure::write('debug' , 1);//关闭调试
	}
	
	function index(){}
	
	//获取飞机场 返回项：所有飞机场信息
    function getAirport( ){
		
        $result = $this->Airport->find('all');
		$airport = array();
		$temp = array();
		$ix = 0;
		while( $result[$ix] != null )
		{
			$temp['city'] = $result[$ix]['Airport']['name'];
			$temp['id'] = $result[$ix]['Airport']['id'];
			array_push($airport,$temp);
			$ix ++;
		}
		return $airport;
		
	}
	
	function getAirport0( ){
		
        $result = $this->Airport->find('all');
		$airport = array();
		$temp = array();
		$ix = 0;
		while( $result[$ix] != null )
		{
			$temp['city'] = $result[$ix]['Airport']['name'];
			$temp['id'] = $result[$ix]['Airport']['id'];
			array_push($airport,$temp);
			$ix ++;
		}
		return $airport;
		
	}
	
	function getAirport1( ){
		
		//$aaa = $this->Airport->find('list',array('field'=>array('Airport.name')));
	    //return $aaa;
        $result = $this->Airport->find('all');
		$airport = array();
		$temp = array();
		$ix = 0;
		while( $result[$ix] != null )
		{
			$temp['city'] = $result[$ix]['Airport']['name'];
			$temp['id'] = $result[$ix]['Airport']['id'];
			array_push($airport,$temp);
			$ix ++;
		}
		return $airport;
		
	}
	
	//获取指定订票id的座位信息 返回项：座位列表
    function getSeatInfo( $id ){
        
        
        $book = $this->BookInfo->find('first',
			array('conditions' => 
				array(
					'BookInfo.id'=> $id
				)
			)
		);
    
    $flight = $this->Flight->findById($book['BookInfo']['flight']);
    
		$now = date('Y-m-d');//当前日期    
    $date = $flight['Flight']['date'];//起飞时间
    
    $nowStamp = strtotime($now);
    $dateStamp = strtotime($date);
    $diff = $dateStamp - $nowStamp;

    if($diff<3600*24) {
      return false;
    }
    
		$array  = array();
		$seat = $book['BookInfo']['seat'];
		$seat = explode(',',$seat);
		$ix = 0;
		while( $seat[$ix] )
		{	
			$array[$ix]['label'] = $seat[$ix];
			$ix ++ ;
		}
		
		return $array;
		
	}
	
	//获取用户订票信息 返回项：用户订票信息
    function getBookInfo( $id ){
		
        $user = $this->BookInfo->find('all',
			array('conditions' => 
				array(
					'BookInfo.user'=> $id
				)
			)
		);
		
		$array  = array();
		$ix = 0;
		while( $user[$ix] )
		{
			$array[$ix] = $user[$ix]['BookInfo'];
			$array[$ix]['flight_info'] = $user[$ix]['Flight']['flight'];
			$ix++;
		}
		return $array;
		
	}
	
	//获取航班 输入项：出发地点，终点，时间(  日期 ) 返回项：航班列表
    function getResult( $start, $end, $time ){
		
        $flights = $this->Flight->find('all',
			array('conditions' => 
				array(
					'Flight.start'=> $start,
					'Flight.end'=> $end,
					'Flight.date' => $time
				)
			)
		);
		
		$array = array();
		
		$ix = 0;
		while( $flights[$ix] )
		{
			$array[$ix] = $flights[$ix]['Flight'];//一条记录，以下是引用外键。
			$array[$ix]['start'] = $flights[$ix]['Start']['name'];
			$array[$ix]['end'] = $flights[$ix]['End']['name'];
			$array[$ix]['plane'] = $flights[$ix]['Plane']['model'];
			$ix ++;
		}
		
		return $array;
		
	}
	
	function getResultAll(  ){
		
        $flights = $this->Flight->find('all');
		
		$array = array();
		
		$ix = 0;
		while( $flights[$ix] )
		{
			$array[$ix] = $flights[$ix]['Flight'];//一条记录，以下是引用外键。
			$array[$ix]['start'] = $flights[$ix]['Start']['name'];
			$array[$ix]['end'] = $flights[$ix]['End']['name'];
			$array[$ix]['plane'] = $flights[$ix]['Plane']['model'];
			$ix ++;
		}
		
		return $array;
		
	}
	
	//获取指定航班信息  输入项：航班ID号  返回项：航班信息列表，航班所属飞机信息列表
	function getFlightInfo( $id ){
	    
		$flight = $this->Flight->find('first', 
			array(
			    'conditions' => array(
				    'Flight.id' => $id
					)
				)
			);
        return $flight['Flight']['id'];
	}
	
	function getFlightInfo1( $id ){
	    
		$flight = $this->Flight->find('first', 
			array(
			    'conditions' => array(
				    'Flight.id' => $id
					)
				)
			);
		$flight['Flight']['start'] = $flight['Start']['id'];
		$flight['Flight']['end'] = $flight['End']['id'];
        return $flight['Flight'];
	}
	
	//订票  输入项：航班ID号，用户ID号，座位列表，订票数量  返回项：订票成功或者失败原因
	function orderTickets( $id, $userId, $seat, $quantity ){
		
		$seat1 = explode(',',$seat);
		
		
		$firstNum = 0;
		$secondNum = 0;
		$thirdNum = 0;
		        //计算定票信息中头等舱，二等舱，三等舱的数目
        for($k = 0; $k < $quantity; $k++){
			
		    $str = substr($seat1[$k],0,1);
			if($str == "A") 
				$firstNum++;
			else if($str == "B") 
				$secondNum++;
            else if($str == "C") 
				$thirdNum++;		
		}
		
		$this->Flight->id=$id;
		$booked= $this->Flight->field('booked');
		$fli = $this->Flight->field('flight');
		$time = $this->Flight->field('date');
		$plane = $this->Flight->field('plane');
		$start = $this->Flight->field('start');
		$end = $this->Flight->field('end');
		$start_time = $this->Flight->field('start_time');
		$end_time = $this->Flight->field('end_time');
		$first_class = $this->Flight->field('first_class');
		$second_class = $this->Flight->field('second_class');
		$third_class = $this->Flight->field('third_class');
		/////////////////////////////////////////////////////////////////////////////
		$fprice = $this->Flight->field('fprice');
		$sprice = $this->Flight->field('sprice');
		$tprice = $this->Flight->field('tprice');
		
		$flight = array('Flight'=>
						   array('flight'=>$fli,
						         'date'=>$time,
								 'plane'=>$plane,
								 'start'=>$start,
								 'end'=>$end,
								 'start_time'=>$start_time,
								 'end_time'=>$end_time,
								 'first_class'=>($first_class - $firstNum ),
								 'fprice'=>$fprice,
								 'second_class'=>($second_class - $secondNum),
								 'sprice'=>$sprice,
								 'third_class'=>($third_class - $thirdNum),
								 'tprice'=>$tprice,
							     //'booked'=>($booked.','.$seat)
							  )
						);
						if($booked==null)
						$flight['Flight']['booked']=$seat;
						else
						$flight['Flight']['booked']=($booked.','.$seat);
						
		//保存更新记录
        $this->modifyFlight($id,$flight);
		
		$time = date("Y-m-d H:i:s");   //获取当前时间
		$bookInfo = array('BookInfo'=>
						array(
						    'flight'=>$id,
							'user'=>$userId,
							'order_time'=>$time,
							'seat'=>$seat,
							'quantity'=>$quantity,
							'price'=>$firstNum*$fprice+$secondNum*$sprice+$thirdNum*$tprice
							)
						);
		
       if( $this->BookInfo->save($bookInfo,false)){
		   return true;
	   }
	   else return false;
		
	}
	
	//退票  必须项：订票ID号  可选项：部分退票的座位号和数量  返回项：退订成功或者失败原因
	function unsubTickets( $id, $seat = NULL, $quantity = NULL ){
	    
		if(!empty($id)){
		    $this->BookInfo->id = $id; 
		    $flightId= (int)$this->BookInfo->field('flight');
			if($seat==NULL&&$quantity ==-1)
			{
				$seat=$this->BookInfo->field('seat');
			}
			
		    $seat1 = explode(',',$seat);
			if($quantity == -1)
				$quantity=count($seat1);
		
		    $firstNum = 0;
		    $secondNum = 0;
		    $thirdNum = 0;
		        //计算退票信息中头等舱，二等舱，三等舱的数目
            for($k = 0; $k < $quantity; $k++){
			
		        $str = substr($seat1[$k],0,1);
			    if($str == "A") $firstNum++;
			    else if($str == "B") $secondNum++;
                else if($str == "C") $thirdNum++;		
		    }
		
		

		

		
		    //修改Flight
		    //$seat1 = explode(',',$seat);
			
			    //取出匹配id=$flightId记录的所有的值
		    $this->Flight->id=$flightId;
		    //$booked= $this->Flight->field('booked');
		    $booked= $this->Flight->field('booked');
			
	        $fli = $this->Flight->field('flight');
		    $time = $this->Flight->field('date');
		    $plane = $this->Flight->field('plane');
		    $start = $this->Flight->field('start');
		    $end = $this->Flight->field('end');
		    $start_time = $this->Flight->field('start_time');
		    $end_time = $this->Flight->field('end_time');
		    $first_class = $this->Flight->field('first_class');
			$fprice=$this->Flight->field('fprice');
		    $second_class = $this->Flight->field('second_class');
			$sprice=$this->Flight->field('sprice');
		    $third_class = $this->Flight->field('third_class');
			$tprice=$this->Flight->field('tprice');
            $booked1 = explode(',',$booked)	;
			
            $i =count($booked1);
	        $j = count($seat1);
			    
				//把航班的座位号重置
		    for($k = 0; $k < $j; $k++){
			    for($h = 0; $h < $i; $h++){
				    if($booked1[$h] == $seat1[$k])
				        unset($booked1[$h]);
			    }
		    }
			
			
		    $booked2 = implode(',',$booked1);
			    //更新记录
		    $flight = array('Flight'=>
						   array('flight'=>$fli,
						         'date'=>$time,
								 'plane'=>$plane,
								 'start'=>$start,
								 'end'=>$end,
								 'start_time'=>$start_time,
								 'end_time'=>$end_time,
								 'first_class'=>($first_class + $firstNum ),
								 'fprice'=>$fprice,
								 'second_class'=>($second_class + $secondNum),
								 'sprice'=>$sprice,
								 'third_class'=>($third_class + $thirdNum),
								 'tprice'=>$tprice,
							     'booked'=>$booked2
							  )
						);
						
				//保存更新记录
            $this->modifyFlight($flightId,$flight);
			
			 //通知排队人
            $quene = $this->Quene->find('all', 
			    array(
			        'conditions' => array(
				        'Quene.flight' => $flightId
					)
				)
			);
		
		    $userid = $quene[0]['Quene']['user'];
			$queneNum = (int)$quene[0]['Quene']['seat_num'];
			//return $queneNum;
		
		    $flight1 =  $this->Flight->find('all', 
			    array(
			        'conditions' => array(
				        'Flight.id' => $flightId
					)
				)
			);
			
		        //取出所有的剩余票数，包括头等舱，二等舱，三等舱
		    $num = $flight1[0]['Flight']['first_class'] + 
		            $flight1[0]['Flight']['second_class'] + 
					    $flight1[0]['Flight']['third_class'];
		
		    
			    //获取用户的手机号码
		    $this->User->id = $userid; 
		    //$phone = $this->User->field('mobile_phone');
			
		
		        //根据剩余票数的情况发送短信给用户
		    if($num > $queneNum && $queneNum!=0){
		        $message = "您所排队的航班现在有票，您现在可以去办理买票";
		        $this->notifyNext($userid,$message);
			}
		    else if($num < $queneNum){
			    $message = "您所排队的航班现在有票，但是剩余的票不够您所排队预定的票，您现在可以去办理买票";
     		    $this->notifyNext($userid,$message);
		    }
		
		    //修改订票信息
			    //取出bookinfo匹配id=$id记录的所有的值
	        $this->BookInfo->id=$id;
		    $flight = $this->BookInfo->field('flight');
		    $user = $this->BookInfo->field('user');
		    $order_time = $this->BookInfo->field('order_time');
		    $seat2 = $this->BookInfo->field('seat');
		    $bookNum = $this->BookInfo->field('quantity');
		
		    $seat3 = explode(',',$seat2);
		
		
		    $i =count($seat3);
	        $j = count($seat1);
		
		        //重置订票座位
		    for($k = 0; $k < $j; $k++){
			    for($h = 0; $h < $i; $h++){
				    if($seat3[$h] == $seat1[$k])
				        unset($seat3[$h]);
			    }
		    }
			
		
		    $seat4 = implode(',',$seat3);
		
		        //更新记录
	        $bookinfo = array('BookInfo'=>
						array('flight'=>$flight,
						    'user'=>$user,
						    'order_time'=>$order_time,
						    'seat'=>$seat4,
							'quantity'=>($bookNum-$quantity)
							)
						);
				//保存更新记录
		    //$this->modifyBookInfo($id,$bookinfo);
			if($bookinfo['BookInfo']['quantity']==0)
				$this->BookInfo->del($id);	
			else		
				$this->modifyBookInfo($id,$bookinfo);
			//$this->BookInfo->del($id);
			
			return true;
		}
		else 
		    return false;
	}
	
	//修改航班信息
	function modifyFlight( $id, $flight){
        
		if(!empty($id)){
		    
            $this->Flight->id=$id;
            $this->Flight->save($flight,false);
			return true;
		}
		else{
			return false;
		}
	}
	
    //修改订票信息
	function modifyBookInfo( $id, $bookinfo){
        //$bookinfo['BookInfo']['seat']="";
		
		if(!empty($id)){
		    

            $this->BookInfo->id=$id;
            if($this->BookInfo->save($bookinfo,false))
			//return $this->BookInfo->seat;
			return true;
			else
			return 'false1';
		}
		else{
			return false;
		}
	}

	
	//通知排队人  输入项：用户id号，通知信息  返回项：通知成功或者失败原因
	function notifyNext( $id, $message ){
 
       
        $this->User->id = $id; 
		$phone = $this->User->field('mobile_phone');
		$message  = iconv("UTF-8","GB2312//TRANSLIT",$message);//TRANSLIT会自动将不能直接转化的字符变成一个或多个近似的字符
		//$string = "http://sms.api.bz/fetion.php?username=13416147450&password=200818&sendto=$phone&message=$message";
	    //if(file_get_contents($string) )return true;
		//else return false;
		
		/*$tomail='@qq.com';
		$subject='';
		$text='';
		if(mail($tomail,$subject,$text))//函数有5个参数前3个是必填参数。第一个参数表示目的地址，第二个参数表示主题，第三个参数表示内容。
		{
			return true;
		}
		else return false;*/
		
		/* SMTP Options */
		$this->Email->smtpOptions = array(
				'port'=>'25',         
				//'timeout'=>'30',         
				'host' => 'smtp.163.com',
				'username'=>'flightbook',
				'password'=>'c12249',
				//'client' => 'smtp_helo_hostname'
		);
		/* Set delivery method */
		$this->Email->delivery = 'smtp';

		$this->Email->from='<flightbook@163.com>';
		$this->Email->to='<'.$this->User->field('email').'>';
		$this->Email->subject = 'flightbook';
		if($this->Email->send($message))
		return true;
		else return false;
		
	}
	
	//排队  输入项：航班ID号，用户ID号，订票数量  存入数据库时应该加上“排队时间”  
	//返回项：排队成功或者失败原因  
	function addQuene( $id, $userId, $quantity ){
	  
	       	$quene = array('Quene'=>
						   array('flight'=>$id,
							     'user'=>$userId,
							     'seat_num'=>$quantity
							  )
						);
			if( $this->Quene->save($quene,false)){
		        return true;
	        }
	        else 
				return false;	   
	}
    
}
?>